package com.wxapp.common.util.http;

import com.wxapp.common.base.util.jackson.JacksonUtil;
import com.wxapp.common.constant.pojo.vo.HttpRequestVo;
import com.wxapp.common.util.check.CheckUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Map;

/**
 * @author lgl
 * @Description http请求工具包
 * @Datetime 2022/4/23 11:56
 * @Modified By
 */
public class HttpRequestUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpRequestUtil.class);
    private static final RestTemplate restTemplate = new RestTemplate();

    private HttpRequestUtil() {
    }

    /**
     * TODO 请求
     */
    public static <T> T request(HttpRequestVo<T> requestVo) {
        try {
            var url = urlAppendValue(requestVo.getUrl(), requestVo.getUrlAppend());
            HttpEntity httpEntity = new HttpEntity<>(requestVo.getData(), requestVo.getHeader());
            String exchange;
            if (CheckUtil.isNotNullObject(requestVo.getUrlAppend())) {
                exchange = restTemplate.exchange(url, requestVo.getMethod(), httpEntity, String.class, requestVo.getUrlAppend()).getBody();
            } else {
                exchange = restTemplate.exchange(url, requestVo.getMethod(), httpEntity, String.class).getBody();
            }
            log.info("请求调用接口：{}", JacksonUtil.toJSONString(exchange));
            if (exchange == null) {
                throw new RuntimeException("请求调用接口出错");
            }
            return JacksonUtil.parseObject(exchange,requestVo.getResponseType());
        } catch (Exception e) {
            log.error("请求调用接口出错：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     *  url 处理
     */
    private static String urlAppendValue(String url, Map<String, Object> urlAppend) {
        if (CheckUtil.isNotNullMap(urlAppend)) {
            StringBuilder urlAppendValue = new StringBuilder();
            urlAppend.keySet().forEach(s-> urlAppendValue.append(s).append("=").append("{").append(s).append("}&"));
            return url + "?" + urlAppendValue.substring(0, urlAppendValue.length() - 1);
        }
        return url;
    }
}
